<template>
  <div class="request-definitions">
    <header class="mb-8">
      <h1 class="glow-text">请求定义</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <div class="relative">
          <input
            type="text"
            class="input pr-10"
            placeholder="搜索请求定义..."
            v-model="searchQuery"
          />
          <svg class="w-5 h-5 absolute right-3 top-2.5 text-light-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="methodFilter">
            <option value="all">所有方法</option>
            <option value="GET">GET</option>
            <option value="POST">POST</option>
            <option value="PUT">PUT</option>
            <option value="DELETE">DELETE</option>
          </select>
        </div>
      </div>

      <div class="flex space-x-2">
        <router-link to="/request/definitions/create" class="btn btn-primary">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
          </svg>
          创建请求定义
        </router-link>
        <button @click="fetchDefinitions" class="btn btn-outline">
          <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          刷新
        </button>
      </div>
    </div>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="filteredDefinitions.length === 0" class="text-center py-12 text-light-dark">
      暂无请求定义，请创建请求定义
    </div>

    <div v-else class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b border-dark-light">
            <th class="py-3 px-4 text-left">名称</th>
            <th class="py-3 px-4 text-left">方法</th>
            <th class="py-3 px-4 text-left">URL</th>
            <th class="py-3 px-4 text-left">描述</th>
            <th class="py-3 px-4 text-left">创建时间</th>
            <th class="py-3 px-4 text-left">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="definition in filteredDefinitions"
            :key="definition._id"
            class="border-b border-dark-light hover:bg-dark-darker"
          >
            <td class="py-3 px-4">{{ definition.name }}</td>
            <td class="py-3 px-4">
              <span :class="{
                'badge badge-blue': definition.method === 'GET',
                'badge badge-green': definition.method === 'POST',
                'badge badge-purple': definition.method === 'PUT',
                'badge badge-orange': definition.method === 'DELETE',
                'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(definition.method)
              }">{{ definition.method }}</span>
            </td>
            <td class="py-3 px-4 font-mono text-sm truncate max-w-xs">{{ definition.url }}</td>
            <td class="py-3 px-4 truncate max-w-xs">{{ definition.description || '无描述' }}</td>
            <td class="py-3 px-4 text-light-dark">{{ formatTime(definition.created_at) }}</td>
            <td class="py-3 px-4">
              <router-link :to="`/request/definitions/${definition._id}`" class="text-primary hover:text-primary-light mr-2" title="查看详情">
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                </svg>
              </router-link>
              <router-link :to="`/request/definitions/${definition._id}/execute`" class="text-accent-blue hover:text-accent-blue/80 mr-2" title="执行">
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </router-link>
              <button
                @click="deleteDefinition(definition._id)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="flex justify-between items-center mt-6">
        <div class="text-light-dark">
          共 {{ pagination.total }} 条记录，第 {{ pagination.page }} / {{ pagination.pages }} 页
        </div>
        <div class="flex space-x-2">
          <button
            @click="changePage(pagination.page - 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page <= 1"
          >
            上一页
          </button>
          <button
            @click="changePage(pagination.page + 1)"
            class="btn btn-outline py-1 px-3"
            :disabled="pagination.page >= pagination.pages"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { requestApi } from '../../api';

// 状态变量
const loading = ref(false);
const searchQuery = ref('');
const methodFilter = ref('all');

// 请求定义列表
const definitions = ref<any[]>([]);

// 分页
const pagination = ref({
  page: 1,
  page_size: 10,
  total: 0,
  pages: 1
});

// 过滤请求定义
const filteredDefinitions = computed(() => {
  let result = definitions.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(definition =>
      definition.name?.toLowerCase().includes(query) ||
      definition.url?.toLowerCase().includes(query) ||
      definition.description?.toLowerCase().includes(query)
    );
  }

  // 方法过滤
  if (methodFilter.value !== 'all') {
    result = result.filter(definition => definition.method === methodFilter.value);
  }

  return result;
});

// 获取请求定义列表
const fetchDefinitions = async () => {
  try {
    loading.value = true;
    const response = await requestApi.getDefinitions({
      page: pagination.value.page,
      page_size: pagination.value.page_size
    });
    
    if (response && typeof response === 'object') {
      if (Array.isArray(response.definitions)) {
        definitions.value = response.definitions;
      }
      
      pagination.value = {
        page: response.page || 1,
        page_size: response.page_size || 10,
        total: response.total || 0,
        pages: response.pages || 1
      };
    } else {
      // 模拟数据
      definitions.value = [
        {
          _id: '101',
          name: '获取用户信息',
          method: 'GET',
          url: 'https://api.example.com/users/123',
          description: '获取指定ID的用户详细信息',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
          },
          body: null,
          created_at: new Date(Date.now() - 86400000).toISOString(),
          updated_at: new Date(Date.now() - 86400000).toISOString()
        },
        {
          _id: '102',
          name: '创建订单',
          method: 'POST',
          url: 'https://api.example.com/orders',
          description: '创建新订单',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
          },
          body: JSON.stringify({
            user_id: 123,
            items: [
              { product_id: 1, quantity: 2 },
              { product_id: 3, quantity: 1 }
            ]
          }),
          created_at: new Date(Date.now() - 172800000).toISOString(),
          updated_at: new Date(Date.now() - 172800000).toISOString()
        },
        {
          _id: '103',
          name: '更新支付状态',
          method: 'PUT',
          url: 'https://api.example.com/payments/456',
          description: '更新支付状态为已完成',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
          },
          body: JSON.stringify({
            status: 'completed',
            transaction_id: 'tx_123456'
          }),
          created_at: new Date(Date.now() - 259200000).toISOString(),
          updated_at: new Date(Date.now() - 259200000).toISOString()
        },
        {
          _id: '104',
          name: '删除用户',
          method: 'DELETE',
          url: 'https://api.example.com/users/789',
          description: '删除指定ID的用户',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
          },
          body: null,
          created_at: new Date(Date.now() - 345600000).toISOString(),
          updated_at: new Date(Date.now() - 345600000).toISOString()
        },
        {
          _id: '105',
          name: '获取订单状态',
          method: 'GET',
          url: 'https://api.example.com/orders/status',
          description: '获取所有订单的状态统计',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
          },
          body: null,
          created_at: new Date(Date.now() - 432000000).toISOString(),
          updated_at: new Date(Date.now() - 432000000).toISOString()
        }
      ];
      
      pagination.value = {
        page: 1,
        page_size: 10,
        total: definitions.value.length,
        pages: 1
      };
    }
  } catch (error) {
    console.error('获取请求定义列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > pagination.value.pages) return;
  pagination.value.page = page;
  fetchDefinitions();
};

// 删除请求定义
const deleteDefinition = async (id: string) => {
  if (!confirm('确定要删除该请求定义吗？此操作不可恢复。')) return;

  try {
    await requestApi.deleteDefinition(id);
    fetchDefinitions();
  } catch (error: any) {
    console.error('删除请求定义失败:', error);
    alert(`删除请求定义失败: ${error.response?.data?.error || error.message}`);
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 监听过滤器变化
watch([searchQuery, methodFilter], () => {
  // 如果过滤器变化，重置到第一页
  if (pagination.value.page !== 1) {
    pagination.value.page = 1;
    fetchDefinitions();
  }
});

// 生命周期钩子
onMounted(() => {
  fetchDefinitions();
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
